package cn.msqweb.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.msqweb.entity.SysUserRole;
import cn.msqweb.mapper.SysUserRoleMapper;
import cn.msqweb.service.SysUserRoleService;
import cn.msqweb.util.AuthUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.msqweb.entity.SysUser;
import cn.msqweb.service.SysUserService;
import cn.msqweb.mapper.SysUserMapper;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author 20120
* @description 针对表【sys_user(系统用户)】的数据库操作Service实现
* @createDate 2024-06-19 18:15:11
*/
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService{

    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private BCryptPasswordEncoder passwordEncoder;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;
    @Resource
    private SysUserRoleService sysUserRoleService;


    @Override
    @Transactional
    public Boolean saveSysUser(SysUser sysUser) {
        sysUser.setCreateUserId(AuthUtils.getLoginSecurityUserID());
        sysUser.setCreateTime(new Date());
        sysUser.setShopId(AuthUtils.getLoginShopId());
        sysUser.setPassword(passwordEncoder.encode(sysUser.getPassword()));

        int insert = sysUserMapper.insert(sysUser);
        if (insert > 0) {
            Long userId = sysUser.getUserId();
            // 处理管理员与角色的关系
            // 获取角色id集合
            List<Long> roleIdList = sysUser.getRoleIdList();
            // 判断是否有值
            if (CollectionUtil.isNotEmpty(roleIdList) && roleIdList.size() != 0) {
                List<SysUserRole> sysUserRoleList = new ArrayList<>();
                // 循环遍历角色id集合
                roleIdList.forEach(roleId -> {
                    // 创建管理员与角色的关系记录
                    SysUserRole sysUserRole = SysUserRole.builder()
                            .userId(userId)
                            .roleId(roleId).build();
                    sysUserRoleList.add(sysUserRole);
                });
                // 批量添加管理员与角色关系
                sysUserRoleService.saveBatch(sysUserRoleList);
            }
        }
        return insert>0;
    }

    @Override
    public SysUser querySysUserDetailByUserId(Long userId) {
        // 根据标识查询管理员信息
        SysUser sysUser = sysUserMapper.selectById(userId);
        // 根据管理员标识查询管理员与角色的关系记录
        List<SysUserRole> sysUserRoleList = sysUserRoleMapper.selectList(new LambdaQueryWrapper<SysUserRole>()
                .eq(SysUserRole::getUserId, userId)
        );
        if (CollectionUtil.isNotEmpty(sysUserRoleList) && sysUserRoleList.size() != 0) {
            // 从管理员与角色关系集合中获取角色id集合
            List<Long> roleIdList = sysUserRoleList.stream().map(SysUserRole::getRoleId).collect(Collectors.toList());
            sysUser.setRoleIdList(roleIdList);
        }
        return sysUser;
    }

    @Override
    @Transactional
    public Boolean modifySysUser(SysUser sysUser) {
        Long userId = sysUser.getUserId();
        // 删除用户原有的角色关系
        sysUserRoleMapper.delete(new LambdaQueryWrapper<SysUserRole>()
                .eq(SysUserRole::getUserId,userId)
        );
        // 获取角色id集合
        List<Long> roleIdList = sysUser.getRoleIdList();
        // 判断是否有值
        if (CollectionUtil.isNotEmpty(roleIdList) && roleIdList.size() != 0) {
            List<SysUserRole> sysUserRoleList = new ArrayList<>();
            // 循环遍历角色id集合
            roleIdList.forEach(roleId -> {
                // 创建管理员与角色的关系记录
                SysUserRole sysUserRole = SysUserRole.builder()
                        .userId(userId)
                        .roleId(roleId).build();
                sysUserRoleList.add(sysUserRole);
            });
            // 批量添加管理员与角色关系
            sysUserRoleService.saveBatch(sysUserRoleList);
        }
        // 修改管理员信息
        // 获取新密码
        String newPassword = sysUser.getPassword();
        if (StringUtils.hasText(newPassword)) {
            sysUser.setPassword(passwordEncoder.encode(newPassword));
        }
        return sysUserMapper.updateById(sysUser)>0;
    }

    @Override
    @Transactional
    public Boolean removeSysUserByUserIds(List<Long> userIds) {
        // 批量删除管理员与角色的关系
        sysUserRoleMapper.delete(new LambdaQueryWrapper<SysUserRole>()
                .in(SysUserRole::getUserId,userIds)
        );
        // 批量删除管理员
        return sysUserMapper.deleteBatchIds(userIds)==userIds.size();
    }
}




